package com.zhong.gang.applib.ui.matching;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.tools.ToastUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhong.gang.applib.R;
import com.zhong.gang.applib.databinding.ActivityMatchingBinding;
import com.zhong.gang.applib.http.BaseDataBean;
import com.zhong.gang.applib.base.act.ActBaseRefresh;
import com.zhong.gang.applib.config.Config;
import com.zhong.gang.applib.http.HttpUtils;
import com.zhong.gang.applib.ui.view.RightTitleView;
import com.zhong.gang.applib.utils.ScanUtils;

import java.util.ArrayList;
import java.util.List;

public class MatchingAct extends  ActBaseRefresh<ActivityMatchingBinding, MatchingAdapter>
        implements MatchingAdapter.OnItemChildClickListener, TextWatcher {

    public static final void openAct(Activity activity,String url
            ,boolean isLogin,String token,String userID,String roleId,boolean showScan,boolean showRemark,int code,boolean isPost){
        Intent intent = new Intent(activity, MatchingAct.class);
        intent.putExtra(Config.URL,url);
        intent.putExtra(Config.IS_LOGIN,isLogin);
        intent.putExtra(Config.TOKEN,token);
        intent.putExtra(Config.USER_ID,userID);
        intent.putExtra(Config.ROLE_ID,roleId);
        intent.putExtra(Config.SHOW_SCAN,showScan);
        intent.putExtra(Config.ISPOST,isPost);
        intent.putExtra(Config.SHOW_REMARK,showRemark);
        activity.startActivityForResult(intent,code);
    }

    @Override
    public int LayoutRes() {
        return R.layout.activity_matching;
    }

    @NonNull
    @Override
    public String CreateTitle() {
        return "手机号匹配货主信息";
    }

    @Override
    public void initView() {
        bind.setAct(this);
        bind.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        initrefrsh(null,new MatchingAdapter(),bind.recyclerView);
        adapter.setOnItemChildClickListener(this);
        bind.phone.addTextChangedListener(this);
        bind.phone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“搜索”键*/
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    String key = bind.phone.getText().toString().trim();
                    if(TextUtils.isEmpty(key)){
                        ToastUtils.s(MatchingAct.this,"请输入您想要搜索的信息");
                        return true;
                    }
                    hideKeyboard();
                    onRefresh();
                    return true;
                }
                return false;
            }
        });
        if (getIntent().getBooleanExtra(Config.SHOW_SCAN,false)){
            RightTitleView rightTitleView = new RightTitleView(this);
            rightTitleView.setImgRes(R.mipmap.icon_title_scan);
            getTitleBar().setRightView(rightTitleView);
            rightTitleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ScanUtils.openScan(MatchingAct.this,Config.SCAN);
                }
            });
        }


        getData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideKeyboard();
    }

    public  void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }

    @Override
    public void getData() {
        super.getData();
        if (getIntent().getBooleanExtra(Config.ISPOST,true)){
            HttpUtils.post(getIntent().getStringExtra(Config.URL),getIntent().getBooleanExtra(Config.IS_LOGIN,false)
                    ,getIntent().getStringExtra(Config.TOKEN),getIntent().getStringExtra(Config.ROLE_ID),getIntent().getStringExtra(Config.USER_ID))
                    .addParams("phone",bind.phone.getText().toString())
                    .build().execute(new CallBack());
        }else {
            HttpUtils.get(getIntent().getStringExtra(Config.URL),getIntent().getBooleanExtra(Config.IS_LOGIN,false)
                    ,getIntent().getStringExtra(Config.TOKEN),getIntent().getStringExtra(Config.ROLE_ID),getIntent().getStringExtra(Config.USER_ID))
                    .addParams("phone",bind.phone.getText().toString())
                    .build().execute(new CallBack());
        }

    }

    private class CallBack  extends ActCallBack<BaseDataBean<List<MatchingBean>>>{
        @Override
        public void onResponse(BaseDataBean<List<MatchingBean>> data) throws Exception {
            super.onResponse(data);
            setData(data.getResult());
            bind.recyclerView.setVisibility(View.VISIBLE);
            if (getIntent().getBooleanExtra(Config.SHOW_REMARK,true)) {
                bind.addName.setVisibility(View.GONE);
                bind.nameLayout.setVisibility(View.GONE);
            }
        }

        @Override
        public void onError(String str) {
            showMainFragemt();
            setData(new ArrayList<MatchingBean>());
            if (getIntent().getBooleanExtra(Config.SHOW_REMARK,true)) {
                if (adapter.getData().size() <= 0) {
                    bind.addName.setVisibility(View.VISIBLE);
                    bind.recyclerView.setVisibility(View.GONE);
                }
            }
        }
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        MatchingBean matchingBean = (MatchingBean) adapter.getItem(position);
        Intent intent = new Intent();
        intent.putExtra(Config.USER_IFNO,matchingBean);
        setResult(RESULT_OK,intent);
        closeActivity();
    }

    public void onViewClicked(View view){
        int i = view.getId();
        if (i == R.id.find){
            onRefresh();
        } else if (i == R.id.add) {
            bind.nameLayout.setVisibility(View.VISIBLE);
        } else if (i == R.id.sure) {
            String name = bind.name.getText().toString();
            if (TextUtils.isEmpty(name)) {
                ToastUtils.s(this, "请输入备注信息");
                return;
            }
            Intent intent = new Intent();
            MatchingBean matchingBean = new MatchingBean();
            intent.putExtra(Config.USER_IFNO,matchingBean);
            matchingBean.setRemark(name);
            setResult(RESULT_OK, intent);
            closeActivity();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (bind.phone.getText().toString().endsWith("***###.")){
            bind.phone.setText(bind.phone.getText().toString().trim().replace("***###.",""));
            hideKeyboard();
            onRefresh();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null)
            return;
       if(requestCode == Config.SCAN){
            Bundle bundle = data.getExtras();
            if (bundle == null) {
                return;
            }
            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                String result = bundle.getString(CodeUtils.RESULT_STRING);
                bind.phone.setText(result);
                onRefresh();
            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                ToastUtils.s(this, "解析二维码失败");
            }
        }
    }

}
